using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Data.SqlTypes;
using System.Data.OleDb;
using System.Text;

public partial class Default2 : System.Web.UI.Page
{
    string strPagesetRowId = "data_manipulation_rule";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj = null;
    DataTable dtCtrInfo;
    HDDatabase hdd = null;
    security hdds = null;
    ScreenReader SR = null;
    DataSet dsPageInfo = null;
    DataSet dsReport = new DataSet();

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
        hdd = new HDDatabase();
        hdds = new security();
        SR = new ScreenReader();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["userid"] == null || Session["userid"].ToString() == "")
                Response.Redirect(hdds.SessionExpiryURL);

            if (Request.QueryString["mn"] != null)
                hdds.logMenuClick(Request.QueryString["mn"].ToString());

            if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
            {
                if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
                {
                    lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    wz_DMR.Visible = false;
                    return;
                }
            }

            if (Request.QueryString["mn"] != null)
            {
                if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
                {
                    wz_DMR.Visible = false;
                    lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    return;
                }
            }

            wz_DMR.DisplaySideBar = false;

            if (this.Master.FindControl("Form1") != null)
            {
                frmObj = (HtmlForm)this.Master.FindControl("Form1");
            }

            if (Request.QueryString["pgs_id"] != null)
            {
                strPagesetRowId = Request.QueryString["pgs_id"].ToString();
            }

            
            string strPageSetHeading = hdds.hddb.GetColumnValue("sy_pgs", "pageset_name", "af_row_id='" + strPagesetRowId.Replace("'", "''") + "'");
            lblHeading.Text = "&nbsp;" + GetPageIcons(strPagesetRowId).Text + "&nbsp;<span style='vertical-align:bottom;'>" + strPageSetHeading + "</span>&nbsp;";
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
          /*  #region loading Dataset
            if (dsPageInfo == null)
            {
                PageInfoLoad objPIL = new PageInfoLoad();
                dsePageInfo = objPIL.GetPageSetPageCtrlInfo(strPagesetRowId);
                DataSet dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("dmrupdatefilter");
                DataSet dsPageInfo2 = objPIL.GetPageSetPageCtrlInfo("dmrupdatevalue");
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["Page"].Merge(dsPageInfo2.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo2.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo2.Tables["PageKeys"]);
                dsPageInfo1 = null;
                dsPageInfo2 = null;
            }
            #endregion*/ 

            if (IsPostBack)
            {
               Session["Column_Name"] = Column_Name.SelectedItem.ToString();
               Session["Column_Name"] = Column_Name.SelectedValue.ToString();
            }

            if (!IsPostBack)
            {               
                string sSql = "Select * from sy_obj order by object_name asc";
                loadObjectsinCombo(sSql);

                DataTable dt = new DataTable();
                dt.Columns.Add("No");
                dt.Columns.Add("Column_Name");
                dt.Columns.Add("Condition");
                dt.Columns.Add("Value");
                dt.Columns.Add("Operator");
                dt.Columns.Add("Delete");
                ViewState["CurrentTable"] = dt;
                gridSelect.DataSource = dt;
                gridSelect.DataBind();
                
                string cond = "select * from sy_acr_mem where acr_id ='3123fa00e7b08e2B' order by mem_seq asc";
                loadCondCombo(cond);

                DataTable dt1 = new DataTable();
                dt1.Columns.Add("No");
                dt1.Columns.Add("Column_Name");
                dt1.Columns.Add("Value");
                dt1.Columns.Add("Delete");
                ViewState["btAddSetCurrentTable"] = dt1;
                gridSet.DataSource = dt1;
                gridSet.DataBind();

                //if (!IsPostBack)
               // {
                  //  this.BindData();
                //}
            }            
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("PageLoad : Error : " + ex.Message);
        }      
    }

    private Literal GetPageIcons(string strPagesetRowID) 
    {
        Literal iconlit = new Literal();
        PageIcons icons = new PageIcons();
        try
        {

            string iconpath = icons.geticonsfrompageset(strPagesetRowID.Replace("'", "''"), 2);
            icons = null;

            iconlit.Text = "&nbsp;<img src = " + iconpath + " style='vertical-align:middle;'></img>&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error GetPageIcons:" + ex.Message);
            iconlit.Text = "&nbsp;<img src = " + PageIcons.strdefaulticon.ToString() + "></img>&nbsp; ";
        }
        finally
        {
            icons = null;
        }
        return iconlit;
    }

    protected void wz_DMR_NextButtonClick(object sender, EventArgs e)
    {
        if (wz_DMR.ActiveStepIndex == 0)
        {
            if (rbList.Checked)
            {
                wz_DMR.ActiveStepIndex = 1;
            }
            else
            {
                wz_DMR.ActiveStepIndex = 2;
                Column_Name.Items.Clear();
                cmbConditionSet.Items.Clear();
                string sTable = select_table.SelectedValue.ToString(); 
                string sql = "select * from sy_pg_ctr where page_id=(select af_row_id from sy_pg where object_id=(select object_id from sy_obj where af_row_id='" + sTable + "'))";
                dtCtrInfo = hdd.GetDataTable(sql, sTable);
                Session["dtCtrInfo"] = dtCtrInfo;
                if (dtCtrInfo != null)
                {
                    Column_Name.Items.Add(new ListItem("--Select a Column--", ""));
                    cmbConditionSet.Items.Add(new ListItem("--Select a Column--", ""));
                    for (int i = 0; i < dtCtrInfo.Rows.Count; i++)
                    {
                        ListItem liObject = new ListItem(dtCtrInfo.Rows[i]["control_name"].ToString(), dtCtrInfo.Rows[i]["control_id"].ToString());
                        Column_Name.Items.Add(liObject);
                        cmbConditionSet.Items.Add(liObject);
                    }
                }
            }
        }
    }

    protected void cmb_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindControl bc = new BindControl();
        try
        {
            dtCtrInfo = (DataTable)Session["dtCtrInfo"];
            if (Column_Name.SelectedIndex == -1) return;
            Column_Name.SelectedItem.Value = Session["Column_Name"].ToString();
           
            if (Column_Name.SelectedValue.Trim() == "")
            {
                cmbValue.Items.Clear();
                return;
            }
            string Sql = string.Empty;
            DataRow[] dr = dtCtrInfo.Select("control_id='" + Column_Name.SelectedValue.ToString() + "'");
            if (dr[0]["control_bind_id"].ToString() != null && dr[0]["control_bind_id"].ToString() != "")
            {
                Sql = "select * from sy_bnd where af_row_id ='" + dr[0]["control_bind_id"].ToString() + "'";
                DataRow dr1 = hdd.GetTableRow(Sql);
                if (dr1 != null)
                {
                    Sql = "select " + dr1["bind_text"] + " from " + dr1["bind_table"];
                    DataTable dt = hdd.GetDataTable(Sql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        cmbValue.Items.Clear();
                        cmbValue.Items.Add(new ListItem("--Select a Value--", ""));
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            ListItem liObject = new ListItem(dt.Rows[i][0].ToString(), dt.Rows[i][0].ToString());
                            cmbValue.Items.Add(liObject);
                        }
                    }
                }
            }
            else
            {
                Sql = "select distinct " + Column_Name.SelectedValue.ToString() + " from " + hdd.GetColumnValue("select object_table from sy_obj where af_row_id='"+ select_table.SelectedValue.ToString()+"'");
                DataTable dt = hdd.GetDataTable(Sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    cmbValue.Items.Clear();
                    cmbValue.Items.Add(new ListItem("--Select a Value--", ""));
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ListItem liObject = new ListItem(dt.Rows[i][Column_Name.SelectedValue.ToString()].ToString(), dt.Rows[i][Column_Name.SelectedValue.ToString()].ToString());
                        cmbValue.Items.Add(liObject);
                    }
                }
            }   

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("cmb_SelectedIndexChanged : Error : " + ex.Message);
        }
    }
    protected void wz_DMR_CancelButtonClick(object sender, EventArgs e)
    {
        name.Text = "";
        description.Text = "";
        update_grouping.Text = "";
        rbList.Checked = false;
        rbUpdate.Checked = false;
        rbCreate.Checked = false;
        rbDelete.Checked = false;
        
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        
        if (SaveData())
        {
            string refURL = getRefURL();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    protected bool SaveData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        SR.CreatePageDataTable(dseInputInfo, dsePageInfo.Tables["Page"], dsePageInfo.Tables["PageCtrl"]);
        if (dseInputInfo.Tables[0] != null)
        {
            DataRow dr = dseInputInfo.Tables[0].NewRow();
            dr["select_table"] = select_table.SelectedValue.ToString();
            dr["name"] = name.Text;
            //dr["category"] = category.SelectedItem.ToString();
            dr["description"] = description.Text;
            dr["update_grouping"] = update_grouping.Text;
            if (rbList.Checked)
            {
                dr["Action"] = hdd.GetColumnValue("select mem_id from sy_acr_mem where af_row_id='ef85eebdfdd4e9a3'");
            }
            if (rbUpdate.Checked)
            {
                dr["Action"] = hdd.GetColumnValue("select mem_id from sy_acr_mem where af_row_id='68c64a6fbe930223'");
            }
            dr["owner_id"] = HttpContext.Current.Session["user_afrowid"].ToString();
            dseInputInfo.Tables[0].Rows.Add(dr);
            dseInputInfo.Tables[0].AcceptChanges();
        } 
        if (SR.errormessage != "")
        {
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + SR.errormessage, true); ;
            return false;
        }

        //CommonFunctions.encodeData(dseInputInfo);
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");

        if (blnStatus == false)
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + MA.ErrorMessage, true);
        else
            lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Inserted Successfully.", false);
        return blnStatus;
    }

    private string getRefURL()
    {
        try
        {
            return "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
        }
        catch
        {
            return "";
        }
    }

    private void loadObjectsinCombo(string Sql)
    {
        HDDatabase hd = new HDDatabase();
        try
        {
            DataTable dt = new DataTable();
            Sql = applysecurity(Sql);
            dt = hd.GetDataTable(Sql);
            AddDefaultObjects(ref dt); 
            select_table.Items.Clear();
            select_table.Items.Add(new ListItem("--Select a Table--", ""));
           
            foreach (DataRow dr in dt.Select("", "object_name asc"))
            {
                if (hdds.getObjectRightsForUser(dr["object_id"].ToString(), "read"))
                {
                    ListItem liObject = new ListItem(dr["object_name"].ToString(), dr["af_row_id"].ToString());
                    select_table.Items.Add(liObject);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadObjectsinCombo : Error : " + ex.Message);
        }
    }

    private void loadCondCombo(string condition)
    {
        HDDatabase hd = new HDDatabase();
        try
        {
            DataTable dt = new DataTable();
            condition = applysecurity(condition);
            dt = hd.GetDataTable(condition);
            AddDefaultObjects(ref dt);
            cmbCondition.Items.Clear();
            cmbCondition.Items.Add(new ListItem("--Select a Condition--", ""));
            foreach (DataRow dr in dt.Select("", "mem_seq asc"))
            {
                ListItem liObject = new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString());
                cmbCondition.Items.Add(liObject);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadCondCombo : Error : " + ex.Message);
        }
    }

    private string applysecurity(string sql)
    {
        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                    sAFAdmin += " and " + sCustodianFilter;
                else
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql + " where " + sAFAdmin;
            }
        }
        catch
        {

        }
        return sql;
    }

    private void AddDefaultObjects(ref DataTable dtInput)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string objectids = "";
            if (dtInput != null)
            {
                foreach (DataRow dr in dtInput.Rows)
                {
                    objectids += "'" + dr["object_id"].ToString() + "',";
                }
                if (objectids.EndsWith(","))
                    objectids = objectids.TrimEnd(',');
            }
            string strSQL = "select mem_id,mem_name from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' and mem_value1 not in (" + objectids + ") order by mem_name";
            DataTable dt = HDD.GetDataTable(strSQL);

            if (dt != null)
                if (dt.Rows.Count > 0)
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow drInput = dtInput.NewRow();
                        drInput["object_name"] = dr["mem_name"].ToString();
                        drInput["object_id"] = dr["mem_id"].ToString();
                        dtInput.Rows.Add(drInput);
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDefaultObjects : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    protected void wz_DMR_PreviousButtonClick(object sender, EventArgs e)
    {       
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        dt.Rows.Clear();
        dt.AcceptChanges();
        gridSelect.DataSource = dt;  
        gridSelect.DataBind();
        DataTable dt1 = (DataTable)ViewState["btAddSetCurrentTable"];
        dt1.Rows.Clear();
        dt1.AcceptChanges();
        gridSet.DataSource = dt1;
        gridSet.DataBind();
    }

    protected void wz_DMR_ActiveStepChanged(object sender, EventArgs e)
    {
    } 
    protected void txtUpdate_Grouping_TextChanged(object sender, EventArgs e)
    {

    }
    protected void wz_DMR_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {

    }
    protected void wz_DMR_FinishButtonClick(object sender, EventArgs e)
    {
    }

    private void setInitialRow()
     {       
         DataTable dt = (DataTable)ViewState["CurrentTable"];
         DataRow dr = null;
         if (dt != null)
         {
                 dr = dt.NewRow();
                 int rowCount = this.gridSelect.Rows.Count +1;    
                 dr["No"] = rowCount;
                 dr["Column_Name"] = Column_Name.SelectedItem.ToString();
                 dr["Condition"] = cmbCondition.SelectedValue.ToString();
                 dr["Value"] = cmbValue.SelectedValue.ToString();
                 if (rbOR.Checked)
                 {
                     dr["Operator"] = "OR";
                 }
                 else if (rbAND.Checked)
                 {
                     dr["Operator"] = "AND";
                 }
                 dr["Delete"] = "";
                 dt.Rows.Add(dr);
                 dt.AcceptChanges();


                 ViewState["CurrentTable"] = dt;
                 this.gridSelect.Visible = true;
                 gridSelect.DataSource = dt;
                 gridSelect.DataBind();

                 dt = gridSelect.DataSource as DataTable;             
         }       
    }
   
    protected DataTable dt
    {
        set { ViewState.Add("dt", value); }
        get { return (DataTable)ViewState["dt"]; }
    }
    protected DataTable dt1
    {
        set { ViewState.Add("dt1", value); }
        get { return (DataTable)ViewState["dt1"]; }
    }
  
    private void btAddSetInitialRow()
    {
        DataTable dt1 = (DataTable)ViewState["btAddSetCurrentTable"];
        DataRow dr1 = null;
        
        if (dt1 != null)
        {
            dr1 = dt1.NewRow();
            dr1["No"] = dt1.Rows.Count + 1;
            dr1["Column_Name"] = cmbConditionSet.SelectedItem.ToString();
            dr1["Value"] = txtValueSet.Text;
            dr1["Delete"] = "";
            dt1.Rows.Add(dr1);
            dt1.AcceptChanges();
            ViewState["btAddSetCurrentTable"] = dt1;
            this.gridSet.Visible = true;
            gridSet.DataSource = dt1;
            gridSet.DataBind();
            dt1 = gridSet.DataSource as DataTable;
        }
    }

    protected void btAdd_Click(object sender, EventArgs e)
    {
        setInitialRow();
    }

    protected void btAddSet_Click(object sender, EventArgs e)
    {
        btAddSetInitialRow();
    }

    protected void gridSelect_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //gridSelect.DeleteRow(gridSelect.SelectedIndex);
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        dt.Rows.RemoveAt(e.RowIndex);
        ViewState["CurrentTable"] = dt;
        dt.AcceptChanges();
        gridSelect.DataSource = dt;
        gridSelect.DataBind();
    }

    protected void gridSet_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt1 = (DataTable)ViewState["btAddSetCurrentTable"];
        dt1.Rows.RemoveAt(e.RowIndex);
        ViewState["btAddSetCurrentTable"]=dt1;
        dt1.AcceptChanges();
        gridSet.DataSource = dt1;
        gridSet.DataBind();
    }

    protected void SaveButton_Click(object sender, EventArgs e)
   {

       if (SaveData1())
       {
           string refURL = getRefURL();
           if (refURL.Length > 0)
               Response.Redirect(refURL);
       }
    }
    protected bool SaveData1()
    {
       bool blnStatus = true;
       ScreenReader SR = new ScreenReader();
       SR.CreatePageDataTable(dseInputInfo, dsePageInfo.Tables["Page"], dsePageInfo.Tables["PageCtrl"]);
       if (dseInputInfo.Tables[0] != null)
       {
       }
         


        if (SR.errormessage != "")
        {
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + SR.errormessage, true); ;
            return false;
        }

        //CommonFunctions.encodeData(dseInputInfo);
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");

        if (blnStatus == false)
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + MA.ErrorMessage, true);
        else
            lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Inserted Successfully.", false);
        return blnStatus;
    

        
   }
   /* private void BindData()
    {
        string strConnString = "Data Source=\"10.199.4.53\";User Id=\"MB_DMR_Test_001\";Password=\"MB_DMR_Test_001_123\";Initial Catalog=\"MB_DMR_Test_001\"";
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            string strQuery = "SELECT * FROM bu_dmrupdatefilter";
            SqlCommand cmd = new SqlCommand(strQuery);
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                gridSelect.DataSource = dt;
                gridSelect.DataBind();
            }
        }
    }
    
     Control control = null;
       if (gridSelect.FooterRow != null)
  {
      control = gridSelect.FooterRow;
  }
  else
  {
      control = gridSelect.Controls[0].Controls[0];
  }
  
  string Column_Name = (control.FindControl("Column_Name") as DropDownList).SelectedValue.ToString(); 
  string Condition = (control.FindControl("cmbCondition") as DropDownList).SelectedValue.ToString();
  string Value = (control.FindControl("cmbValue") as DropDownList).SelectedValue.ToString();
  string strConnString = "Data Source=\"10.199.4.53\";User Id=\"MB_DMR_Test_001\";Password=\"MB_DMR_Test_001_123\";Initial Catalog=\"MB_DMR_Test_001\"";
  using (SqlConnection con = new SqlConnection(strConnString))
  {
      using (SqlCommand cmd = new SqlCommand())
      {
          cmd.Connection = con;
          cmd.CommandType = CommandType.Text;
          cmd.CommandText = "INSERT INTO [bu_dmrupdatevalue] VALUES(@column_name, @condition, @value)";
          cmd.Parameters.AddWithValue("@column_name", Column_Name);
          cmd.Parameters.AddWithValue("@condition", Condition);
          cmd.Parameters.AddWithValue("@value", Value);
          con.Open();
          cmd.ExecuteNonQuery();
          con.Close();
      }
  }
  Response.Redirect(Request.Url.AbsoluteUri);
   
     */
}
      
